package com.ipfsemc.ipfsemc.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ipfsemc.ipfsemc.model.UserInfo;
import com.ipfsemc.ipfsemc.service.IUserInfoService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class WxLogin {

    @Autowired
    private QRUtil qrUtil;

    @Autowired
    private DateUtil dateUtil;

    @Autowired
    private ApiUtil apiUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUserInfoService userInfoService;


    //微信公众号
    public static final String APP_ID = "wxfe2516abdf463ba9";     //填写自己的APPID
    public static final String APP_SECRET = "8de23e2b47907401877c0bc35a00899e";   //填写自己的APPSECRET
    private static final String redirect_uri = "http://gl.ipfsemc.com/ipfsemc/login/loginBack";
    private static final String CODE = "code";
    private static final String OPENID = "openid";
    private static final String ACCESS_TOKEN = "access_token";
    private static final String UNION_ID = "unionid";
    private static final String SUBSCRIBE = "subscribe";
    private static final String ENCODING = "UTF-8";


    // 测试环境
    public static final String APP_ID1 = "wx4a7a8696b59b40fe";
    public static final String APP_SECRET1 = "43a41b67717b7cd1a5d2c6e6ecdaf275";

    /**
     * 请求登录地址
     *
     * @param request
     * @param response
     */
    public void WxLogin(HttpServletRequest request, HttpServletResponse response) {
//        UUID uuid = UUID.randomUUID();
        //回调地址（必须在公网进行访问）
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID
                + "&redirect_uri=" + URLEncoder.encode(redirect_uri)
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";
//        Map map = new HashMap();
//        redisTemplate.opsForValue().set(uuid, 1);
//
//        map.put("code", uuid.toString());
//        map.put("url", url);
        //二维码生成
        qrUtil.encodeQrCode(url, response);
    }

    public String wxLogin() {
        //回调地址（必须在公网进行访问）
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID
                + "&redirect_uri=" + URLEncoder.encode(redirect_uri)
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";
        return url;
    }

    /**
     * 微信登录回调地址
     *
     * @param request
     * @param response
     */
    public UserInfo LoginBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1、得到微信返回的code
        String code = request.getParameter(CODE);
        // 2、利用得到的code获取授权token和openid
        JSONObject tokenAndOpenId = getTokenAndOpenId(code);
        String openid = tokenAndOpenId.getString(OPENID);
        String access_token = tokenAndOpenId.getString(ACCESS_TOKEN);
        // 3、获取用户基本信息
        JSONObject userInfo = getUserInfo(openid, access_token);

        System.out.println("【userInfo:】" + userInfo);

//        userInfoService
        // 获取普通token
        JSONObject normalToken = getNormalToken();
        access_token = normalToken.getString(ACCESS_TOKEN);

        // 判断用户是否关注公众号
        JSONObject userInfos = getUserInfos(openid, access_token);

        System.out.println("【userInfos:】" + userInfos);
        String unionid = userInfo.getString(UNION_ID);
        String username = userInfo.getString("nickname");//微信名
        String headimgurl = userInfo.getString("headimgurl");//头像
        UserInfo user = new UserInfo();
        user.setUserId(unionid);
        user.setUserName(username);
        user.setImage(headimgurl);

        if (userInfos.getInteger(SUBSCRIBE) == 0) {
            // 拿到用户唯一标识
            int i = userInfoService.addUser(user);
            response.getWriter().write("<h2><center>您还未注册公众号！</center></h2>");
        } else {
            response.getWriter().write("<h2><center>登录成功！</center></h2>");
        }

        // 向用户推送登录成功消息
        String template_id = "jbIEUk3tGtWcRN4BdDZXkJuvPm-lDf4S4jochh53WGQ";
        String url = "http://weixin.qq.com/download";

        JSONObject data = new JSONObject();
        data.put("first", content("登陆成功！", "red"));
        data.put("keyword1", content("朱士展", "blue"));
        data.put("keyword2", content("1001", "red"));
        data.put("remark", content("您好，您已成功登录易迈云。时间：" + dateUtil.dateFormat(new Date(), dateUtil.format2), "gray"));

        String reqParam = reqParam(openid, template_id, url, data);

        url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        String result = apiUtil.postRequest(url, "json", reqParam, null, ENCODING);
        JSONObject json = JSON.parseObject(result);
        System.out.println("登陆成功：向用户推送消息：" + json);
        // 判断是否发送成功
        // 。。。
        if (json.getInteger("errcode") == 0) {
            System.out.println("推送成功");
        } else {
            System.out.println("推送失败");
        }

//        String redirectUrl = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzU0MTg4NjQ3Nw==&scene=124#wechat_redirect";
        String redirectUrl = "http://gl.ipfsemc.com/ipfsemc";
        response.sendRedirect(redirectUrl);

        return user;
    }


    /**
     * @param request
     * @param response
     * @return
     */
    public ResponseEntity checkWechat(HttpServletRequest request, HttpServletResponse response) {
        // 检测用户是否登录
        return null;
    }

    /**
     * 获取授权token：用来做登录授权操作
     * 和openid
     *
     * @param code
     * @return openid, access_token
     */
    public JSONObject getTokenAndOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID
                + "&secret=" + APP_SECRET
                + "&code=" + code
                + "&grant_type=authorization_code";
        String result = apiUtil.getRequest(url, ENCODING);
        return JSON.parseObject(result);
    }

    /**
     * 获取普通token:用来执行公众号功能调用
     *
     * @return
     */
    public JSONObject getNormalToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + APP_ID +
                "&secret=" + APP_SECRET;
        String result = apiUtil.getRequest(url, ENCODING);
        return JSON.parseObject(result);
    }

    /**
     * 获取微信用户基本信息
     *
     * @param openid
     * @param access_token
     * @return
     */
    public JSONObject getUserInfo(String openid, String access_token) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
                + "&openid=" + openid
                + "&lang=zh_CN";
        String result = apiUtil.getRequest(url, ENCODING);
        return JSON.parseObject(result);
    }

    /**
     * 获取微信用户基本信息：可以获取是否关注公众号
     *
     * @param openid
     * @param access_token
     * @return
     */
    public JSONObject getUserInfos(String openid, String access_token) {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid +
                "&lang=zh_CN";
        String result = apiUtil.getRequest(url, ENCODING);
        return JSON.parseObject(result);
    }

    /**
     * 封装微信请求参数
     *
     * @param touser
     * @param template_id
     * @param url
     * @param data
     * @return
     */
    private String reqParam(String touser, String template_id, String url, JSONObject data) {
        JSONObject reqParam = new JSONObject();
        reqParam.put("touser", touser);
        reqParam.put("template_id", template_id);
        reqParam.put("url", url);
        reqParam.put("data", data);
        return reqParam.toJSONString();
    }

    /**
     * 封装请求参数data中的数据
     *
     * @param value
     * @param color
     * @return
     */
    private JSONObject content(String value, String color) {
        JSONObject param = new JSONObject();
        param.put("value", value);
        param.put("color", color);
        return param;
    }

    /**
     * 发起Http请求, 通过POST方式访问网络用到的方法
     *
     * @param url,请求的URL地址
     * @return 响应后的字符串
     */
    public static JSONObject doPostStr(String url, String outstr) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            httpPost.setEntity(new StringEntity(outstr, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSON.parseObject(result);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObject;

    }

}
